package com.eqdd.yiqidian.ui.companyspace.base

import android.app.Activity
import android.content.Intent
import android.support.v7.widget.RecyclerView
import android.view.View
import com.eqdd.yiqidian.R
import com.eqdd.yiqidian.adapter.slimadapter.SlimInjector
import com.eqdd.yiqidian.base.Config
import com.eqdd.yiqidian.base.loading.INetLoadingView
import com.eqdd.yiqidian.base.loading.waitdialog.DialogHelper
import com.eqdd.yiqidian.bean.rebuild.slimedit.SlimImageSelectBean
import com.eqdd.yiqidian.http.HttpResult
import com.eqdd.yiqidian.http.JsonCallBack
import com.eqdd.yiqidian.kotlin.deleteDialog
import com.eqdd.yiqidian.kotlin.imgPathPreview
import com.eqdd.yiqidian.ui.base.SlimBaseMultiEditActivity
import com.eqdd.yiqidian.utils.ImageUtil
import com.eqdd.yiqidian.utils.PicUtil
import com.luck.picture.lib.PictureSelector
import com.luck.picture.lib.config.PictureConfig
import com.lzy.okgo.OkGo
import com.lzy.okgo.model.HttpParams
import com.lzy.okgo.model.Response
import io.reactivex.Observable
import io.reactivex.ObservableEmitter
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.functions.BiFunction
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.activity_recyclerview.*
import kotlinx.android.synthetic.main.list_item_23.*
import org.jetbrains.anko.sdk25.coroutines.onClick
import org.jetbrains.anko.toast
import java.io.File


/**
 * 企业空间信息基础类
 * Created by jhj on 18-6-23.
 */
abstract class BaseSpaceInfoActivity<T : ISpaceBean<T>> : SlimBaseMultiEditActivity() {

    var dialog: INetLoadingView? = null
    var bean: T? = null
    var type: Int = 0
    var id: Int = -1

    abstract val topbar: String
    abstract val deleteUrl: String
    abstract val updateImgUrl: String
    abstract val updateOtherUrl: String
    abstract val updateIdFieldName: String //修改时，条目id对应的字段名称
    abstract val deleteIdFieldName: String //删除时，条目id对应的字段名称
    open val isHasImg = true // 是否有图片
    open val isImgCircle: Boolean = false // true-显示圆图;false-显示方图

    val updateOtherParams = HttpParams()


    override fun initBinding() {
        clearData()
        setContentView(R.layout.activity_recyclerview)
        type = intent.getIntExtra(Config.TYPE, 0)
        initTopTitleBar(View.VISIBLE, topbar)
        bean = intent.getSerializableExtra("data") as T?
        id = intent.getIntExtra(Config.ID, -1)
        if (bean == null && id == -1) {
            toast("获取详情失败")
            finish()
            return
        }

    }

    override fun initRecyclerView(): RecyclerView {
        return recyclerView
    }

    override fun itemClick(p: Int) {

    }


    override fun initData() {
        super.initData()
        slimAdapterEx.register(R.layout.layout_image_selected, SlimInjector<SlimImageSelectBean> { data, injector ->
            if (isImgCircle) {
                injector?.imageCircle(R.id.iv_add, data?.image)
            } else {
                injector?.image(R.id.iv_add, data?.image)
            }
            injector?.text(R.id.tv_label, data?.title)
                    ?.clicked(R.id.iv_add) {
                        if (type == 0) {
                            PicUtil.single(this@BaseSpaceInfoActivity, true)
                        } else {
                            data?.image?.let { it1 -> imgPathPreview(it1) }
                        }
                    }
        })
    }


    override fun setView() {
        super.setView()

        if (type == 0) {
            dialog = DialogHelper(this)
            btn_submit.text = "修改"
            btn_submit.visibility = View.VISIBLE
            btn_submit.onClick {
                if (isHasImg) {
                    dialog?.showLoading()
                    Observable
                            .zip(updateOther(), updateImage(), BiFunction<Int, Int, Any> { t1, t2 ->
                                if (t1 == -1) {
                                    false
                                } else t2 != -1


                            })
                            .subscribeOn(Schedulers.io())
                            .observeOn(AndroidSchedulers.mainThread())
                            .subscribe {
                                if (!(it as Boolean))
                                    toast("修改失败")
                                else
                                    toast("修改成功")
                                dialog?.hideLoading()
                                setResult(Activity.RESULT_OK)
                                finish()
                            }
                } else {
                    updateOther()
                }

            }

            initTopRightText("删除") {
                deleteDialog(deleteUrl, "是否删除${bean?.title
                        ?: "该数据"}", deleteIdFieldName to bean?.id)
            }
        }


    }


    private fun updateImage(): Observable<Int> {
        var subscribe: ObservableEmitter<Int>? = null
        val o = Observable.create<Int> {
            subscribe = it
        }
        var file: File?
        val params = HttpParams()
        slimAdapterEx.getDataItem(0).tag?.let {
            file = File(it as String)
            params.put("image", file)
        }

        OkGo.post<HttpResult<*>>(updateImgUrl)
                .params("userGuid", user.guid)
                .params("companyId", user.companyId)
                .params(updateIdFieldName, bean?.id ?: 0)
                .params(params)
                .execute(object : JsonCallBack<HttpResult<*>>() {
                    override fun onSuccess(response: Response<HttpResult<*>>?) {
                        val result = response?.body()
                        if (result?.status == 200 || result?.status == 201) {
                            subscribe?.onNext(1)
                            subscribe?.onComplete()
                        } else {
                            subscribe?.onNext(-1)
                            subscribe?.onComplete()
                        }
                    }

                    override fun onFinish() {
                        super.onFinish()
                        subscribe?.onNext(-1)
                        subscribe?.onComplete()
                    }
                })


        return o
    }

    private fun updateOther(): Observable<Int> {
        var subscribe: ObservableEmitter<Int>? = null
        val o = Observable.create<Int> {
            subscribe = it
        }

        OkGo.post<HttpResult<*>>(updateOtherUrl)
                .params("userGuid", user.guid)
                .params("companyId", user.companyId)
                .params(updateIdFieldName, bean?.id ?: 0)
                .params(updateOtherParams())
                .execute(object : JsonCallBack<HttpResult<*>>() {
                    override fun onSuccess(response: Response<HttpResult<*>>?) {
                        val result = response?.body()
                        if (result?.status == 200) {
                            subscribe?.onNext(1)
                            subscribe?.onComplete()
                        } else {
                            subscribe?.onNext(-1)
                            subscribe?.onComplete()
                        }
                    }

                    override fun onFinish() {
                        super.onFinish()
                        subscribe?.onNext(-1)
                        subscribe?.onComplete()
                    }
                })
        return o
    }


    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (isHasImg && resultCode == RESULT_OK && requestCode == PictureConfig.CHOOSE_REQUEST) {
            val localMedias = PictureSelector.obtainMultipleResult(data)
            if (isImgCircle) {
                ImageUtil.setCircleImage(localMedias?.get(0)?.compressPath, iv_add)
            } else {
                ImageUtil.setImage(localMedias?.get(0)?.compressPath, iv_add)
            }
            slimAdapterEx.getDataItem(0).tag = localMedias?.get(0)?.compressPath

        }
    }

    abstract fun updateOtherParams(): HttpParams

}